package com.cxhome.cxinfox.accountRecord;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.traffic.managent.base.BaseService;
import com.traffic.managent.base.Paginator;
import com.traffic.managent.model.account.Account;
import com.traffic.managent.model.customer.Customer;
import com.traffic.managent.model.system.Department;
import com.traffic.managent.model.system.User;
import com.traffic.managent.util.StringUtils;
import com.traffic.managent.util.UtilsUtils;

/**
 * 客户业务处理类。
 * 
 */
public class AccountService extends BaseService {

	private static Logger log = Logger.getLogger(AccountService.class);
	public static final AccountService service = new AccountService();
	
	
	
	/**
	 * 查询list
	 * @param model
	 * @param paginator
	 * @param orderSql
	 * @param customerId
	 * @param departmentId
	 * @return
	 */
	public Page<Account> paginate(Account model, Paginator paginator, String orderSql, String customerId,
			String departmentId) {

		String startTime = model.getStr("startTime");
		String endTime = model.getStr("endTime");
		String username = model.getStr("createName");
		String customerName = model.getStr("customerId");

		// 用户没有绑定账户时
		StringBuilder idsStr = new StringBuilder();
		if (StringUtils.isEmpty(customerId)) { // 管理员用户登录时,没有账户信息,根据组织机构来查询数据
			// 数据权限
			// 之前的查询是直接根据组织机构来模糊查询的" and u.departmentId like #'$departmentId$%'#
			// ",
			// 但是实际上由于组织机构拖动改变, 模糊查询查询出来的数据会错乱掉.
			// ***从组织机构数据表中查询出该组织结构所有的实际子组织机构id(含本身)***
			String tempIdsStr = Department.dao.queryChildIds(departmentId);
			String tempIdsStr1 = tempIdsStr.replaceAll(",", "','");
			if (tempIdsStr1.contains(",")) {
				idsStr = new StringBuilder("('" + tempIdsStr1 + "')");
			} else {// 组织机构只有一个时查询语句会报错
				idsStr = new StringBuilder("('" + tempIdsStr1 + "','" + tempIdsStr1 + "')");
			}
			// 加入组织结构参数
			departmentId = idsStr.toString();
			customerId = "";
		} else {
			// 有绑定账户时就只能够查询该账户的充值记录
			departmentId = "";
		}

		StringBuilder sql = new StringBuilder(" from ( "
				+ "SELECT distinct a.createtime,a.amount AS amount1, 0.0 AS amount2,a.createName,a.currentAmount,a.currentGive, b.customerName, a.type,a.remark "
				+ "FROM cx_account_record a, cx_customer_info b , cx_user u "
				+ "WHERE a.customerId = b.customerId AND a.status = '0' AND a.type = '0' AND a.amount IS NOT NULL and u.customerId = b.customerId ");

		if (StringUtils.isEmpty(customerId)) {
			sql.append(" AND u.departmentId in " + idsStr);
		} else {
			sql.append(" AND b.customerId = '" + customerId + "'");
		}
		if (StringUtils.isNotEmpty(customerName)) {
			sql.append(" and b.customerName like '" + customerName + "'");
		}
		if (StringUtils.isNotEmpty(username)) {
			sql.append(" and a.createName like '" + username + "'");

		}
		if (StringUtils.isNotEmpty(startTime)) {
			sql.append(" AND a.createTime >= '" + startTime + "'");

		}
		if (StringUtils.isNotEmpty(endTime)) {
			sql.append(" AND a.createTime <= '" + endTime + "'");
		}

		sql.append(" union all ");

		sql.append(
				" SELECT distinct a.createtime, 0.0 AS amount1, a.amount AS amount2,a.createName,a.currentAmount,a.currentGive, b.customerName, a.type,a.remark "
						+ "FROM cx_account_record a, cx_customer_info b , cx_user u  "
						+ "WHERE a.customerId = b.customerId AND a.status = '0' AND a.type = '1' AND a.amount IS NOT NULL and u.customerId = b.customerId ");

		if (StringUtils.isEmpty(customerId)) {
			sql.append(" AND u.departmentId in " + idsStr);
		} else {
			sql.append(" AND b.customerId = '" + customerId + "'");
		}
		if (StringUtils.isNotEmpty(customerName)) {
			sql.append(" and b.customerName like '" + customerName + "'");
		}
		if (StringUtils.isNotEmpty(username)) {
			sql.append(" and a.createName like '" + username + "'");
		}
		if (StringUtils.isNotEmpty(startTime)) {
			sql.append(" AND a.createTime >= '" + startTime + "'");
		}
		if (StringUtils.isNotEmpty(endTime)) {
			sql.append(" AND a.createTime <= '" + endTime + "'");
		}

		sql.append(") tempA ");
		sql.append(orderSql);
		

		return Account.dao.paginate(paginator, "select tempA.*  ", sql.toString());

	}
	
	

	/**
	 * 充值
	 * 
	 */
	@Before(Tx.class)
	public void chargeR(String customerId, String chargeAmount, String giftAmount, String remark, User user) {
		synchronized (this) {

			if (null != chargeAmount && !"".equals(chargeAmount) && !"0.00".equals(chargeAmount)) {
				Account account = new Account();
				chargeAmount = chargeAmount.replaceAll(",", "");
				account.set("ids", UtilsUtils.getRandomId(30));
				account.set("customerId", customerId);
				account.set("type", 0);
				account.set("status", 0);
				account.set("createName", user.get("username"));
				account.set("createTime", new Date());
				account.set("amount", chargeAmount);
				Db.update("update cx_customer_info set amount = (IFNULL(amount,0) + ?)  where customerId = ?",
						Double.parseDouble(chargeAmount), customerId);
				Customer customer = Customer.dao.findById(customerId);
				account.set("currentAmount", customer.get("amount"));
				account.set("currentGive", customer.get("giveAmount"));
				account.set("remark", remark);
				account.save();
			}

			if (null != giftAmount && !"".equals(giftAmount) && !"0.00".equals(giftAmount)) {
				Account account = new Account();
				giftAmount = giftAmount.replaceAll(",", "");
				account.set("ids", UtilsUtils.getRandomId(30));
				account.set("customerId", customerId);
				account.set("type", 1);
				account.set("status", 0);
				account.set("createName", user.get("username"));
				account.set("createTime", new Date());
				account.set("amount", giftAmount);
				Db.update("update cx_customer_info set giveAmount = (IFNULL(giveAmount,0) + ?) where customerId = ?",
						Double.parseDouble(giftAmount), customerId);

				Customer customer = Customer.dao.findById(customerId);

				account.set("currentAmount", customer.get("amount"));
				account.set("currentGive", customer.get("giveAmount"));
				account.save();
			}

		}
	}

	/**
	 * 设置信用额和信用预警额
	 * 
	 */
	public void setCredit(String customerId, String creditAmount, String warnAmount, User user) {
		synchronized (this) {
			if (null != creditAmount && !"".equals(creditAmount) && !"0.00".equals(creditAmount)) {
				creditAmount = creditAmount.replaceAll(",", "");
				Account account = new Account();
				account.set("ids", UtilsUtils.getRandomId(30));
				account.set("customerId", customerId);
				account.set("type", 3);
				account.set("status", 0);
				account.set("createName", user.get("username"));
				account.set("createTime", new Date());
				account.set("amount", creditAmount);
				account.save();
				Db.update(
						"update cx_customer_info set creditAmount = (IFNULL(creditAmount,0) + ?) where customerId = ?",
						Double.parseDouble(creditAmount), customerId);

			}

			if (null != warnAmount && !"".equals(warnAmount) && !"0.00".equals(warnAmount)) {
				warnAmount = warnAmount.replaceAll(",", "");
				Account account = new Account();
				account.set("ids", UtilsUtils.getRandomId(30));
				account.set("customerId", customerId);
				account.set("type", 4);
				account.set("status", 0);
				account.set("createName", user.get("username"));
				account.set("createTime", new Date());
				account.set("amount", warnAmount);
				account.save();
				Db.update("update cx_customer_info set warnAmount = (IFNULL(warnAmount,0) + ?) where customerId = ?",
						Double.parseDouble(warnAmount), customerId);
			}
			// Customer customer = Customer.dao.findById(customerId);
		}
	}
}
